package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.ShopMapper;
import com.example.crossborderecommerce.service.IShopService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/shop")
public class ShopController {
    @Resource
    IShopService shopService;
    @Resource
    ShopMapper shopMapper;
    
    /**
     * 添加店铺
     * @param shop
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Shop shop) {
        shop.setAuthorizationTime(LocalDateTime.now());
        boolean res = shopService.save(shop);
        if(res) {
            return Result.success("添加店铺成功！");
        }
        return Result.error("添加店铺失败！");
    }

    /**
     * 获得店铺总数
     * @return
     */
    @GetMapping("/count")
    public Result count() {
        return Result.success(shopService.count());
    }

    /**
     * 删除店铺
     * @param shop
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Shop shop) {
        boolean res = shopService.removeById(shop);
        if(res) {
            return Result.success("删除店铺成功！");
        }
        return Result.error("删除店铺失败！");
    }

    /**
     * 查询所有店铺
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Shop> shopList = shopService.list();
        if(shopList != null) {
            return Result.success("查询所有店铺成功！", shopList);
        }
        return Result.error("查询所有店铺失败！");
    }

    /**
     * 删除一系列店铺
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> shopIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = shopService.removeByIds(shopIds);
        if(res) {
            return Result.success("删除店铺成功");
        }
        return Result.error("删除店铺失败！");
    }

    /**
     * 修改店铺
     * @param shop
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Shop shop) {
        boolean res = shopService.saveOrUpdate(shop);
        if (res) {
            return Result.success("修改店铺成功！");
        }
        return Result.error("修改店铺失败！");
    }


    /**
     * 分页查询所有店铺
     * @param name
     * @param contactName
     * @param platform
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String contactName,
                           @RequestParam(defaultValue = "全部") String platform,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        if(!platform.equals("全部")) {
            queryWrapper.eq("platform", platform);
        }
        queryWrapper.like("name", name);
        queryWrapper.like("contact_name", contactName);
        Page<Shop> shopPage = shopService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success("成功查询所有店铺！",shopPage);
    }

    /**
     * 导出店铺信息
     * @param name
     * @param contactName
     * @param platform
     * @param response
     * @return
     */
    @GetMapping("exportShopList")
    public Result exportShopList(@RequestParam(defaultValue = "") String name,
                                         @RequestParam(defaultValue = "") String contactName,
                                         @RequestParam(defaultValue = "全部") String platform,
                                         HttpServletResponse response) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        if(!platform.equals("全部")) {
            queryWrapper.eq("platform", platform);
        }
        queryWrapper.like("name", name);
        queryWrapper.like("contact_name", contactName);
        List<Shop> shopList = shopService.list(queryWrapper);
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("店铺名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("店铺地址");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("店铺平台");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("负责人");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("联系电话");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("授权时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < shopList.size(); i++) {
            row = sheet.createRow(i + 1);
            Shop shop = shopList.get(i);
            row.createCell((short) 0).setCellValue(shop.getId());
            row.createCell((short) 1).setCellValue(shop.getName());
            row.createCell((short) 2).setCellValue(shop.getAddress());
            row.createCell((short) 3).setCellValue(shop.getPlatform());
            row.createCell((short) 4).setCellValue(shop.getContactName());
            row.createCell((short) 5).setCellValue(shop.getContactPhone());
            try {
                Date authorizeTime = inputDateFormat.parse(shop.getAuthorizationTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 6).setCellValue(outputDateFormat.format(authorizeTime));
            } catch (ParseException e) {
                row.createCell((short) 6).setCellValue(shop.getAuthorizationTime().toString());
            }
        }
        String fileName = "exportShopList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportShopList");
    }

    /**
     * 获取客户订单中涉及到的所有店铺
     * @return
     */
    @GetMapping("/getShopsInCustomerOrder")
    public Result getShopsInCustomerOrder() {
        List<Shop> shopList = shopMapper.getShopsInCustomerOrder();
        if(shopList == null) {
            return Result.error("查询客户订单失败！");
        }
        return Result.success(shopList);
    }
}
